package com.school.movie.common.interceptor;

import com.school.movie.business.web.model.vo.Manager;
import com.school.movie.business.web.model.vo.UserVo;
import com.school.movie.common.utils.ContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Objects;

import static com.school.movie.common.constant.Constants.User.Authorization.CERTIFY;


/**
 * 权限拦截器
 *
 * @author zhaoren
 */
@Component
@Slf4j
public class PermissionInterceptor extends HandlerInterceptorAdapter {

    @Value("${FRONT}")
    private String FRONT;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        String servletPath = request.getServletPath();
        Manager manager = ContextUtils.getManagerInfo();
        UserVo user = ContextUtils.getWebUserInfo();

        //前台需要验证的地方
        String[] pathVariables = servletPath.split("/");
        if (pathVariables.length >= 4) {
            if (pathVariables[3].equals(CERTIFY)) {
                if (Objects.nonNull(user)) {
                    return true;
                }
                //转发到前台登录页面
                StringBuilder url = new StringBuilder(basePath + "page/login" + "?redirect=" + request.getRequestURI());
                Enumeration<String> parameterNames = request.getParameterNames();
                boolean hasParameter = false;
                while (parameterNames.hasMoreElements()) {
                    if (!hasParameter) {
                        url.append("?");
                    }
                    hasParameter = true;
                    String parameterName = parameterNames.nextElement();
                    url.append(parameterName).append("=").append(request.getParameter(parameterName));
                    url.append("&");
                }
                if (hasParameter) {
                    url = new StringBuilder(url.substring(0, url.length() - 1));
                }
                log.info("重定向url=====>" + url);
                response.sendRedirect(url.toString());
                return false;
            }
        }

        //前台不需要验证的url
        if (servletPath.contains(FRONT)) {
            return true;
        }

        //判断后台管理员是否登录，如果没有登录重定向到登录页面
        if (manager == null) {
            response.sendRedirect(basePath + "login.jsp");
            return false;
        }

        return true;
    }

}
